package ua.org.groovy.gs.core;

import java.awt.Graphics2D;

import ua.org.groovy.gs.botworld.event.Event;

import groovy.lang.Closure;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyObjectSupport;

public abstract class Agent extends GroovyObjectSupport {
	private GroovyObject controller;
	
	/*public final void fireEvent(String eventName, Object[] params) {
		try {
			if (params == null) {
				((Closure)this.getProperty("on" + eventName)).call();
			} else {
				((Closure)this.getProperty("on" + eventName)).call(params);		
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}*/
	
	public final void fireEvent(Event event) {
		Closure handler = (Closure)this.getProperty("on" + event.getName());
		if (handler != null)
			handler.call(event);
	}
	
	public Agent() {
	}
	
	public Agent(String controllerScriptText) {
		setController(controllerScriptText);
	}
	
	public void setController(GroovyObject controller) {
		this.controller = controller;
		controller.setProperty("agent", this);
		controller.invokeMethod("run", new Object[]{});
	}

	public void setController(String controllerText) {
		try {
			controller = getControllerByScriptText(controllerText);
			controller.setProperty("agent", this);
			controller.invokeMethod("run", new Object[]{});
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public GroovyObject getController() {
		return controller;
	}
	
	private GroovyObject getControllerByScriptText(String script) 
			throws InstantiationException, IllegalAccessException {
		ClassLoader parent = getClass().getClassLoader();
		GroovyClassLoader loader = new GroovyClassLoader(parent);
		Class groovyClass = loader.parseClass(script);
		
		return (GroovyObject) groovyClass.newInstance();
	}
	
	public abstract void update(int deltaMillis);
	
	public abstract void draw(Graphics2D g);
}